import 'server-only';

import type { Socket } from 'socket.io';
import env from './env';

export const socketsMap = new Map<string, Socket[]>(new Map());

export const sendSocketData = <T>({
  toIds,
  event,
  data,
}: {
  toIds: string[];
  event: string;
  data: T;
}) => {
  fetch(`${env.APP_URL}/api/socket`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      toIds,
      event,
      data,
    }),
  });
};

export const checkOnline = async (userId: string) => {
  const res = await fetch(`${env.APP_URL}/api/socket?userId=${userId}`);
  const data = await res.json();
  return data === 'online';
};
